package com.atguigu.service.impl;

import com.alibaba.fastjson2.JSON;
import com.atguigu.entity.product.Category;
import com.atguigu.mapper.CategoryMapper;
import com.atguigu.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<Category> selectOneCategory() {
        String str = redisTemplate.opsForValue().get("category:one");
        List<Category> categoryList = null;
        if (str!= null && !str.isEmpty()) {
            categoryList = JSON.parseArray(str, Category.class);
        } else {
            categoryList = categoryMapper.selectOneCategory();
            redisTemplate.opsForValue().set("category:one", JSON.toJSONString(categoryList), 7, TimeUnit.DAYS);
        }
        return categoryList;
    }

    @Override
    public List<Category> findCategoryTree() {
        List<Category> categoryList = categoryMapper.findAll();
        List<Category> oneList = categoryList.stream()
                .filter(category -> category.getParentId() == 0)
                .collect(Collectors.toList());

        oneList.forEach(oneCategory -> {
            List<Category> twoList = categoryList.stream()
                    .filter(category -> category.getParentId() == oneCategory.getId())
                    .collect(Collectors.toList());
            oneCategory.setChildren(twoList);

            twoList.forEach(towCategory -> towCategory.setChildren(categoryList.stream()
                    .filter(category -> category.getParentId() == towCategory.getId())
                    .collect(Collectors.toList())));
        });
        return oneList;
    }
}
